package bitmap;

import breeze.util.Index;

/**
 * @author com.eureka.wh
 * @since 2019/6/30 9:40
 */
public class BitMap {

    private long[] words;
    private int size;

    public BitMap() {
    }

    public BitMap(int size) {
        this.size = size;
        this.words = new long[(getWordIndex(size - 1) + 1)];
    }

    /**
     * 判断Bitmap某一位的状态
     * @param bitIndex 位图的bitIndex位(bitIndex=0代表Bitmap左数第1位)
     */
    public boolean getBit(int bitIndex) {
        if (bitIndex < 0 || bitIndex > size - 1) {
            throw new IndexOutOfBoundsException("超过Bitmap有效范围");
        }
        int wordIndex = getWordIndex(bitIndex);
        return (words[wordIndex] & (1L << bitIndex)) != 0;
    }

    /**
     * 把Bitmap某一位设置为true
     * @param bitIndex 位图的bitIndex位(bitIndex=0代表Bitmap左数第1位)
     */
    public void setBit(int bitIndex) {
        if (bitIndex < 0 || bitIndex > size - 1) {
            throw new IndexOutOfBoundsException("超过Bitmap有效范围");
        }
        int wordIndex = getWordIndex(bitIndex);
        // |= 按位或操作
        words[wordIndex] |= (1L << bitIndex);
    }

    /**
     * 定位Bitmap某一位所对应的word
     * @param bitIndex 位图的bitIndex位(bitIndex=0代表Bitmap左数第1位)
     */
    private int getWordIndex(int bitIndex) {
        // 右移动6位，相当于除以64
        return bitIndex >> 6;
    }
}
